<?php

namespace app\impl;

use app\common\model\Project as ProjectModel;
use app\interfaces\Task;
use MongoDB\Bson\ObjectId;
use app\common\business\Answer;
use app\common\lib\ZhyxMongo;
use app\common\model\Follow as FollowModel;
use app\common\model\PushMessage as PushMessageModel;
use app\common\model\FollowPushQuestionnaire as PushQuestionnaireModel;

class SendFollow implements Task
{
    public function run(array $data,string $taskId): ?bool
    {

        try {

            //----------------------------------------------
            $follow_mode = config('dictionary.follow_mode');

            //获取问卷名称
            $project = (new ProjectModel())->where('projectId', $data['projectId'])
                ->field('id,name,parentId,creator_dept_name,creator_name')
                ->find();

            $patients = (new FollowModel())->getConditionData([['id', 'in', $data['patientList']]]);

            $questData      = [];#推送问卷参数
            $followDatas    = [];#随访患者问卷信息参数
            $messageDatas   = [];#推送消息参数
            //$patientIds     = [];#多个患者id参数(发短信用)
            $history        = [];#推送历史
            $pushQuestDatas = [];#推送问卷记录

            foreach ($patients as $key => $val) {

                //follow_history表主键
                $hid = (string)new ObjectId();

                //推送问卷
                $questData[] = [
                    'follow_id'  => $val['id'],
                    'history_id' => $hid,
                    'sex'        => $val['sex'],
                    'age'        => $val['inage'],
                    'name'       => $val['name'],
                    'mobile'     => $val['presentTelphone']??'',
                    'patient_id' => $val['patient_id'],
                    'task_id'    => (string)$val['task_id'],
                    'creator_id' => $data['creator_id'],
                    'creator_name' => $data['username'],
                    'patientDeptId' => $val['patientDeptId']??'',
                    'patientdeptName' => $val['patientdeptName']??''
                ];

                //更新随访患者模板信息
                $followDatas[] = [
                    'id'           => $val['id'],
                    'type'         => (int)$data['mode'],#推随访类型 1微信，2短信，3微信/短信，4电话
                    'pushtime'     => date('Y-m-d'),
                    'pushdatetime' => date('Y-m-d H:i:s'),
                    'projectId'    => $data['projectId'],
                    'projectName'  => $project['name'],
                    'pushStaff'    => $data['user_id'],
                    'mode'         => (int)$data['mode'],#推送方式
                    'mobile'       => (string)$val['presentTelphone']??''
                ];

                //随访记录
                $history[] = [
                    '_id'             => $hid,
                    'follow_id'       => (string)$val['id'],
                    'mode'            => (int)$data['mode'],
                    'modeName'        => $follow_mode[$data['mode']],
                    'pushtime'        => date('Y-m-d'),
                    'pushdatetime'    => date('Y-m-d H:i:s'),
                    'projectId'       => $data['projectId'],
                    'projectName'     => $project['name'],
                    'staffId'         => $data['user_id'],
                    'staffName'       => $data['username'],
                    'staffDepartment' => $data['department_id'],
                    'staffDoctorCode' => $data['doctor_code'],
                    'staffDepartmentName' => $data['department_name'],
                    'task_id'         => (string)$val['task_id'],
                    'taskname'        => $val['taskname'],
                    'status'          => 0,
                    'deleted_at'      => $data['deleted_at'],
                    'created_at'      => time(),
                    'updated_at'      => time(),
                    'year_month'      => (int)date("Ym"),
                    'year'            => (int)date("Y"),
                    'patientId'       => $val['patient_id'],
                    'pid'             => $val['pid'],
                    'diagnosis'       => $val['diagnosis']??'',
                ];

                //推送消息
                $messageDatas[] = [
                    'type'        => 1,
                    'typeName'    => '随访',
                    'pushtime'    => date('Y-m-d'),
                    'pushdatetime'=> date('Y-m-d H:i:s'),
                    'patientId'   => $val['patientId'],
                    'projectId'   => $data['projectId'],
                    'creator_id'  => $data['creator_id'],
                    'projectName' => $project['name'],
                    'content'     => '您好'.$val['name'].',为您推送'.$project['name'].'随访内容',
                    'deleted_at'  => $data['deleted_at'],
                    'follow_id'   => $val['id'],
                    'created_at'  => time(),
                    'history_id'  => $hid,
                    'isview'      => 0,
                    'category'    => 'Patient'
                ];

                //推送问卷记录
                $pushQuestDatas[] = [
                    'create_date' => $val['create_date'],
                    'task_id'     => (string)$val['task_id'],
                    'taskname'    => $val['taskname'],
                    'project_id'  => $project['id'],
                    'projectId'   => $data['projectId'],
                    'projectName' => $project['name'],
                    'parentId'    => $project['parentId'],
                    'dept_id'     => $data['department_id'],
                    'creator_dept_name' => $project['creator_dept_name'],
                    'creator_name' => $project['creator_name'],
                    'deleted_at'   => $data['deleted_at'],
                    'created_at'   => time(),
                    'updated_at'   => time(),
                ];
            }

            $questDatas['projectId']  = $data['projectId'];
            $questDatas['creator_id'] = $data['creator_id'];
            $questDatas['putChanel']  = $data['putChanel'];
            $questDatas['deleted_at'] = $data['deleted_at'];
            $questDatas['creator_dept_id'] = $data['department_id'];
            $questDatas['creator_dept_name'] = $data['department_name'];

            //推送问卷队列参数
            $questDatas['patientList'] = $questData;


            //---------------------------------------------
           
            (new FollowModel())->saveAll($followDatas);
            (new PushMessageModel())->saveAll($messageDatas);
            
            foreach ($history as $k => &$v)
            {
                 $v["_id"] = new ObjectId($v["_id"]);
                 $v["follow_id"] = new ObjectId($v["follow_id"]);
                 $v["task_id"] = new ObjectId($v["task_id"]);
            }

           ZhyxMongo::getInstance()->setCollection('follow_history')->insertMany($history);
           (new Answer())->initQuestion($questDatas);

           //短信随访
            if (in_array($data['mode'],[2,3]))
            {
                //回填短信发送状态
                $status = [];
                foreach ($followDatas as $key => $val)
                {
                    if (!empty($val['mobile'])){
                        $status[] = [
                            'id' => $val['id'],
                            'smsStatus' => 1,
                        ];
                    }
                }

                if (!empty($status)) {
                    (new FollowModel())->saveAll($status);
                }
            }else{
                $status = [];
                foreach ($followDatas as $key => $val)
                {
                    $status[] = [
                        'id' => $val['id'],
                        'wechatStatus' => 1,
                    ];
                }

                if (!empty($status)) {
                    (new FollowModel())->saveAll($status);
                }
            }
            (new PushQuestionnaireModel())->saveAll($pushQuestDatas);
            return true;
        } catch (\Exception $exception) {
            \think\facade\Log::record("推送随访问卷异常:" . $exception->getMessage(), "error");
        }
        return true;
    }
}
